package com.changgou.system.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.system.pojo.Admin;
import com.changgou.system.service.AdminService;
import com.changgou.system.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {


    @Autowired
    private AdminService adminService;


    /**
     * @param admin
     * @return com.changgou.entity.Result
     * @description: 添加管理员
     * @author 大佬味的小男孩
     * @date 2020/07/17 23:07
     */
    @PostMapping("add")
    public Result add(@RequestBody Admin admin) {
        //判断验证码不为空
        //判断用户名或者密码不为空
        if (admin.getLoginName() == null || admin.getPassword() == null) {
            return new Result(false, StatusCode.ERROR, "用户名或者密码不为空");
        }
        //
        adminService.add(admin);
        return new Result(true, StatusCode.OK, "添加管理员成功");
    }

    /**
     * @param admin
     * @return com.changgou.entity.Result
     * @description: 管理员登陆
     * @author 大佬味的小男孩
     * @date 2020/07/18 09:39
     */
    @PostMapping("login")
    public Result login(@RequestBody Admin admin) {
        //判断验证码不为空

        //判断用户名或者密码不为空
        if ("".equals(admin.getLoginName()) || "".equals(admin.getPassword())) {
            return new Result(false, StatusCode.ERROR, "用户名或者密码不为空");
        }
        boolean flog = adminService.login(admin);
        if (!flog) {
            return new Result(false, StatusCode.LOGINERROR, "登录失败，用户或密码错误");
        }
        //用户登录成功后 发token
        HashMap<String, String> map = new HashMap<>();
        map.put("loginName", admin.getLoginName());
        //根据用户名 和UUID 和时间 生成一个jwt返回给客户端
        String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), admin.getLoginName(), null);
        map.put("token", jwt);
        return new Result(true, StatusCode.OK, "登录成功", map);
    }


    /**
     * @param id
     * @return com.changgou.entity.Result
     * @description: 根据id删除管理者
     * @author 大佬味的小男孩
     * @date 2020/07/18 00:02
     */
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        Integer i = adminService.delete(id);
        if (i == 0) {
            return new Result(false, StatusCode.ERROR, "删除失败");
        }
        return new Result(true, StatusCode.OK, "删除成功");
    }

    /**
     * @param
     * @return com.changgou.entity.Result
     * @description: 查询所有
     * @author 大佬味的小男孩
     * @date 2020/07/18 09:35
     */
    @GetMapping("findAll")
    public Result findAll() {
        List<Admin> adminList = adminService.findAll();
        return new Result(true, StatusCode.OK, "查询成功", adminList);
    }


}
